#!/bin/bash

#exit with non-zero exit code if any process fails
set -e

branch_name="${GITHUB_REF#refs/*/}"

echo "branch_name: ${branch_name}"

#  don't do anything on pull-requests
if [ "${GITHUB_HEAD_REF}" != "" ]
then
    exit 0
elif  [ "${branch_name}" != "master" -o "${GITHUB_REPOSITORY}" != "kitspace/kitspace" ]
then
    echo -e "User-agent: *\nDisallow: /\n" > build/robots.txt
    echo -e "${PREVIEW_DEPLOY_SSH_KEY}" > key-file
    chmod 600 key-file
    # replace all / with .
    folder=${branch_name//\//.}
    UPLOAD_DESTINATION=${UPLOAD_DESTINATION:-ubuntu@preview.kitspace.org:preview/${folder}/}
    rsync --archive --compress --update --delete --recursive -e 'ssh -i key-file -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' build/ "${UPLOAD_DESTINATION}"
    rm -f key-file
else
    mv build/.temp .
    npx netlify deploy --prodIfUnlocked --site $NETLIFY_SITE_ID --auth $NETLIFY_AUTH_TOKEN --dir=build/
    mv .temp build/
fi
